<template>
  <div class="TheCanvas-wrap">
    <div class="TheCanvas" @click="handleClick(null)">
      <component
        v-for="item in widgets"
        :key="item.id"
        :is="item.type"
        :class="[item === currentWidget ? 'TheWidget--active' : '']"
        :config="item"
        :dimension="item.dimension"
        @mousedown.native.stop="handleClick(item)"
        @click.native.stop="handleClick(item)"
      ></component>
      <div class="TheCanvas__bg-grid"></div>
    </div>
  </div>
</template>

<script>
import { dragResize } from "./utils"
export default {
  name: "TheCanvas",
  data() {
    return {}
  },
  computed: {
    widgets() {
      return this.$store.state.widgets
    },
    currentWidget() {
      return this.$store.state.currentWidget
    },
  },
  mounted() {
    dragResize(".TheWidget", this.updateDimension)
  },
  methods: {
    updateDimension(target) {
      const id = Number(target.getAttribute("data-id"))
      var top = Math.round(parseFloat(target.style.top)) || 0
      var left = Math.round(parseFloat(target.style.left)) || 0
      var width = Math.round(parseFloat(target.style.width))
      var height = Math.round(parseFloat(target.style.height))
      this.$store.dispatch("UpdateWidget", {
        dimension: {
          top: top,
          left: left,
          width: width,
          height: height,
        },
        id: id,
      })
    },
    handleClick(widget) {
      this.$store.commit("updateCurrentWidget", widget)
    },
  },
}
</script>

<style lang="scss">
@mixin bg-grid {
  background-image: linear-gradient(90deg, #aaa 1px, transparent 0),
    linear-gradient(0deg, #aaa 1px, transparent 0);
  background-size: 20px 20px;
  opacity: 0.15;
  background-position: 0 0;
}
.TheCanvas-wrap {
  border: 1px solid #aaa;
  overflow: auto;
  margin: 20px;
  .TheCanvas {
    position: relative;
    // width: 1200px;
    height: 1200px;
    background: #fff;
    .TheCanvas__bg-grid {
      @include bg-grid;
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      pointer-events: none;
    }
  }
}
</style>
